//
//  TKYImageCompressTool.m
//  SegmentManage
//
//  Created by apple on 2017/12/15.
//  Copyright © 2017年 铁科院. All rights reserved.
//

#import "TKYImageCompressTool.h"

@implementation TKYImageCompressTool
// 压缩图片
+ (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize withSourceImage:(UIImage *)sourceImage{
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth= width * scaleFactor;
        scaledHeight = height * scaleFactor;
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else if (widthFactor < heightFactor)
        {
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
    UIGraphicsBeginImageContext(targetSize); // this will crop
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width= scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil)
        NSLog(@"could not scale image");
    
    UIGraphicsEndImageContext();
    
    return newImage;
}

+ (CGSize)imageCompress:(UIImage *)image{
    // CGSize size = image.size;
    CGFloat wight = image.size.width > image.size.height ? image.size.width : image.size.height;
    CGFloat scale = 0.0;
    CGFloat scaleWH = 0.0;
    if (wight < 800) {
        scale = 1.0;
        scaleWH = 1.0;
        
    }else if (800 < wight && wight <= 1920){
        scale = 0.5;
        scaleWH = 2;
        
    }else if (1920 < wight && wight <= 2560){
        scale = 0.3;
        scaleWH = 3;
    }else if (2560 < wight && wight <= 3840){
        scale = 0.2;
        scaleWH = 4;
    }else if (wight > 3840){
        scale = 0.1;
        scaleWH = 5;
    }
    
    CGSize size = CGSizeMake(image.size.width / scaleWH, image.size.height / scaleWH);
    // newImage.size = size;
    return  size;
}

@end
